import axios from 'axios'
import { MessageBox, Message } from 'element-ui'

// create an axios instance   http://localhost:xxx/xx/xx封装请求
const service = axios.create({
  baseURL: '/dev-api', // url = base url + request url
  // withCredentials: true, // send cookies when cross-domain requests
  timeout: 5000 // request timeout 设置超时时间 毫秒
})

// request interceptor 请求拦截器
service.interceptors.request.use(
  config => {

    return config
  },
  error => {
    // do something with request error
    console.log(error) // for debug
    return Promise.reject(error)
  }
)

// response interceptor
// 响应拦截器
service.interceptors.response.use(
 
  response => {
    const res = response.data

    // if the custom code is not 20000, it is judged as an error.
    // 20000 正常的业务结果
    if (res.code !== 2000) {
      Message({
        message: res.message || 'Error',
        type: 'error',
        duration: 5 * 1000
      })
      return Promise.reject(new Error(res.message || 'Error'))
    } else {
      return res
    }
  },
  error => {
    console.log('err' + error) // for debug
    Message({
      message: error.message,
      type: 'error',
      duration: 5 * 1000
    })
    return Promise.reject(error)
  }
)

export default service
